using System;
using System.Windows.Forms;
using BizTalk.BuildGenerator.UI.Navigation;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class ApplicationDescriptionControl : UserControl, IWizardControl
    {
        private GenerationArgs _Args;

        public ApplicationDescriptionControl()
        {
            InitializeComponent();
        }

        private void ApplicationDescriptionControl_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                ApplicationsComboBox.Items.AddRange(BizTalkHelper.GetApplications().ToArray());
                SetupControls();
            }
        }

        private void SetupControls()
        {
            if (_Args == null)
                return;
            if (_Args.ApplicationDescription == null)
                return;
            if (_Args.ApplicationDescription.Name == null)
                return;

            int index = ApplicationsComboBox.FindString(_Args.ApplicationDescription.Name);
            if (index >= 0)
                ApplicationsComboBox.SelectedIndex = index;

            if (_Args.OutputFolder == null)
                return;
            else
                OutputDirectoryTextBox.Text = _Args.OutputFolder;

            if (string.IsNullOrEmpty(_Args.SourceCodeRootFolder))
                return;
            else
                SourceCodeRootTextBox.Text = _Args.SourceCodeRootFolder;
        }

        public ApplicationDescription GetDescription()
        {
            return BizTalkHelper.DescribeApplication((string) ApplicationsComboBox.SelectedItem);
        }

        public void RegisterArgs(GenerationArgs args)
        {
            _Args = args;
            SetupControls();
        }

        #region IWizardControl Members

        public MoveNextResult MoveNext()
        {
            _Args.ApplicationDescription = GetDescription();
            _Args.OutputFolder = OutputDirectoryTextBox.Text;
            _Args.SourceCodeRootFolder = SourceCodeRootTextBox.Text;
            
            MoveNextResult result = new MoveNextResult();
            result.CanMoveNext = true;
            return result;
        }

        #endregion

        private void BrowseDirectoryButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
                OutputDirectoryTextBox.Text = folderBrowserDialog.SelectedPath;
        }

        private void BrowseSourceCodeFolderButton_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
                SourceCodeRootTextBox.Text = folderBrowserDialog.SelectedPath;
        }
    }
}